<template>
  <div style="display: inline-block;">
    <a-upload
      name="file"
      list-type="picture-card"
      :file-list="fileListData"
      @preview="handlePreview"
      @change="handleChange"
      :customRequest="customRequest"
    >
      <div v-if="fileListData.length < fileMax">
        <a-icon type="plus"/>
        <div class="ant-upload-text">
          Upload
        </div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { upload } from '@/api/manage'

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
const token = Vue.ls.get(ACCESS_TOKEN)
export default {
  name: 'ImgUpload',
  components: {
  },
  props: {
    source: {
      type: String,
      required: true
    },
    fileMax: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      headers: {
        'Authorization': token
      },
      previewVisible: false,
      previewImage: '',
      action: process.env.VUE_APP_BASE_API + '/file/upload',
      fileListData: []
    }
  },
  methods: {
    setImg (filelist) {
      this.fileListData = filelist
    },
    handleCancel () {
      this.previewVisible = false
    },
    handleChange ({ fileList }) {
      this.fileListData = fileList
      if (this.fileListData.length === 0) {
        this.$emit('change', [{
          fileId: '',
          fileName: '',
          url: ''
        }])
      }
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    customRequest (file) {
      const form = new FormData()
      form.append('file', file.file)
      form.append('source', this.source)
      form.append('code', '')
      upload(form).then(res => {
        const data = res.data
        this.fileListData = [{
          uid: '-1',
          name: data.fileName,
          status: 'done',
          url: data.previewUrl
        }]
        this.$emit('change', [{
          fileId: data.fileId,
          fileName: data.fileName,
          url: data.previewUrl
        }])
      })
    }
  },
  mounted () {
    console.log(this.fileList)
  }
}
</script>
